<template>
  <div>
    <div class="search-content">
      <el-form
        ref="searchForm"
        :inline="true"
        :model="searchContent">
        <el-form-item label="兑换单号：" prop="order_sn">
          <el-input
            class="search-content-input"
            v-model="searchContent.order_sn"
            placeholder="兑换单号">
            </el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="mobile">
          <el-input
            class="search-content-input"
            v-model="searchContent.mobile"
            placeholder="手机号">
            </el-input>
        </el-form-item>
        <!-- <el-form-item label="会员名称：" prop="member_name">
          <el-input
            class="search-content-input"
            v-model="searchContent.member_name"
            placeholder="会员名称">
            </el-input>
        </el-form-item>        -->
        <el-form-item label="使用店铺：" prop="store_name">
          <el-input
            class="search-content-input"
            v-model="searchContent.store_name"
            @focus="checkfocus(1)"
            readonly
            placeholder="使用店铺">
            </el-input>
        </el-form-item>     
        <el-form-item label="兑换时间：" prop="add_time">
          <el-date-picker
            v-model="searchContent.add_time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
            </el-date-picker>
        </el-form-item>    
        <el-form-item label="承担商家：" prop="settlement_store_name">
          <el-input
            class="search-content-input"
            v-model="searchContent.settlement_store_name"
            @focus="checkfocus(2)"
            readonly
            placeholder="承担商家">
            </el-input>
        </el-form-item>         
        <el-form-item label>
          <el-select
            clearable
            v-model="searchContent.is_review"
            placeholder="复核状态">
            <el-option value="0" label="未复核"></el-option>
            <el-option value="1" label="已复核"></el-option>
          </el-select>
        </el-form-item>         
        <el-form-item label>
          <el-select
            clearable
            v-model="searchContent.is_paid"
            placeholder="打款状态">
            <el-option value="0" label="未打款"></el-option>
            <el-option value="1" label="已打款"></el-option>
          </el-select>
        </el-form-item>             
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button type="primary" @click="resetSearchData">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="search-list">
      <el-table
        :data="goodsList"
        border
        :height="oHeight"
        :fit="true"
        header-cell-class-name="hdCellStyle" 
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          align="center"
          type="selection"
          width="55"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="point_ordersn"
          label="兑换单号"
          min-width="140"
          #default="{ row }">
          <span :class="`color-${row.exception_state}`">{{row.point_ordersn}}</span>
          <el-tooltip class="item" effect="dark" content="异常取消" placement="right-start" v-if="row.exception_state == 1">
            <i class="el-icon-question color-1" />
          </el-tooltip>
        </el-table-column>
        <el-table-column
          align="center"
          prop="member_mobile"
          label="手机号"
          min-width="120"
        ></el-table-column>
        <!-- <el-table-column
          align="center"
          prop="member_name"
          label="会员名"
          min-width="80"
        ></el-table-column>    -->
        <el-table-column
          align="center"
          prop="pay_points"
          label="抵扣积分"
          min-width="76"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="settle_store_name"
          label="承担商家"
          min-width="80"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="capture_point"
          label="承担积分"
          min-width="76"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="add_time"
          label="下单时间"
          min-width="130"
          ></el-table-column
        >
        <el-table-column
          align="center"
          label="订单状态"
          min-width="120"
          prop="order_status_desc"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="review_desc"
          label="复核状态"
          min-width="80"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="paid_desc"
          label="打款状态"
          min-width="80"
        >
        </el-table-column>
        <el-table-column
          fixed="right"
          align="center"
          prop="isInitiative"
          label="操作"
          min-width="100"
        >
        <template slot-scope="scope">
          <el-button v-if="scope.row.review_desc=='未复核'" type="primary" @click="buttonDeal(scope.row.id,scope.row.can_not_operate)">复核</el-button>
          <el-button
            v-else
            type="primary"
            @click="billRollback(scope.row.id,scope.row.can_not_operate)">
            撤回
          </el-button>
          <el-button v-if="scope.row.paid_desc=='未打款'" type="primary" @click="buttonPaid(scope.row.id,scope.row.can_not_operate)">打款</el-button>
          <el-button
            v-else
            type="primary"
            @click="paidback(scope.row.id,scope.row.can_not_operate)">
            撤回
          </el-button>          
          </template>
        </el-table-column>
      </el-table>
      <div class="bottom">
        <div class="btn-group">
          <el-button type="primary" class="btn-bottom" @click="expertData"
            >导出检索数据</el-button>
          <el-button type="primary" class="btn-bottom" @click="oneBill"
            >一键复核</el-button>
           <el-button type="primary" class="btn-bottom" @click="pointcalc"
            >积分计算</el-button>
        </div>
        <!--分页部分-->
        <div class="paginationOne">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="searchContent.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="searchContent.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </div>
    <check-store :showStoreBox.sync="showStoreBox"  @chooseStore="getStoreInfo" ></check-store>    
  </div>
</template>
<script>
import { resize } from "@/common/js/height.js";
import checkStore from "@/components/home/check-store.vue";
import { dateFormatter, objScreen } from "@/common/js/util";
export default {
	props: {},
  data() {
    return {
      goodsList: [],
      oHeight: 800,
      searchContent: {
        currentPage: 1,
        pageSize: localStorage.getItem("pageSize") * 1 || 20,
        add_time: "",//时间
        order_sn: "",//订单编号
        member_name: "",//会员名称
        mobile: "",//手机号
        is_settled: 1, //是否结算
        review_page : 1,//是否复核页面
        type : 2,//1积分订单 2是在线支付
        store_id:'',//店铺id
        is_review:'',//是否复核
        is_paid:'',//是否已打款
        order_status:'',//订单状态
        settlement_store_id:'',//承担商家id
        settlement_store_name:'',//承担商家name
      },
      originate: '',
      dialogFormVisible: false,
      codeFileList: [],
      searchObj: {},
      total: 0,
      check: [],
      // review_options:[
      //   {value: 0, value_txt: "未复核"},
      //   {value: 1, value_txt: "已复核"},
      // ],
      // paid_options:[
      //   {value: 0, value_txt: "未复核"},
      //   {value: 1, value_txt: "已复核"},
      // ],
      type_options: [
        // {value: 2, value_txt: "已取消"},
        // {value: 10, value_txt: "已提交,待付款"},
        // {value: 11, value_txt: "已付款,待确认"},
        // {value: 20, value_txt: "确认收款,待发货"},
        {value: 30, value_txt: "已发货,待收货"},
        {value: 40, value_txt: "已完成"},
        // {value: 65, value_txt: "积分已扣,未付款"},
        // {value: 70, value_txt: "已退款"},
        {value: 60, value_txt: "待评价"},
      ],//订单状态
      showStoreBox: false,
    };
  },
  created() {
    this.beforeData();
    this.search();
  },
  components: { checkStore },
  methods: {
    
     //获取所有订单状态
    beforeData() {},
    //获取店铺id
    getStoreInfo(store) {
      if(this.storeType==1){
        this.searchContent.store_name = store.storeName;
        this.searchContent.store_id = store.storeId;
      }else if(this.storeType==2){
        this.searchContent.settlement_store_name = store.storeName;
        this.searchContent.settlement_store_id = store.storeId;
      }

    },
    checkfocus(type){
      this.showStoreBox = true;
      this.storeType = type
    },
    //一键复核
    oneBill() {
      let idArr = [];
      let dataErr = false;
      if (this.check.length === 0) {
        this.$message.warning("请勾选数据");
        return;
      }
       this.check.forEach((item) => {
         console.log(item);
        if (item.settle_desc === "已结算" ) {
          idArr.push(item.id);
        } else {
          dataErr = true;
        }
      });
      if (dataErr) {
        this.$message.error("请选择正确的状态！");
        return;
      }
      for(var item of this.goodsList){
        if(idArr.indexOf(item.id)>=0){
            if(item.can_not_operate){
                   this.$message.error("请选择正确的状态！");
                   return;
            }
        }
      }          
      this.$http.post('/admin/points/index.php?act=PointsSettle&op=quickReview', {ids: idArr,}).then((res) => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.search();
        } else {
          this.$message.warning(res.msg);
        }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },

    //积分计算
    pointcalc(){
      let idArr = [];
      let dataErr = false;
      if (this.check.length === 0) {
        this.$message.warning("请勾选数据");
        return;
      }
       this.check.forEach((item) => {
         console.log(item);
        if (item.settle_desc === "已结算" ) {
          idArr.push(item.id);
        } else {
          dataErr = true;
        }
      });
      if (dataErr) {
        this.$message.error("请选择正确的状态！");
        return;
      }
      var data = {};
      for(let [key,value] of Object.entries(idArr)){
        data['ids['+key+']'] = value
      }
      this.$http.get('/admin/points/index.php?act=PointsSettle&op=pointsCalculate', {params: data}).then((res) => {
        if (res.code === 1) {
          this.$alert(`未复核的${res.data.un_reviewed},未打款的${res.data.un_confirmed}`, {
            confirmButtonText: '确定',
            callback: action => {
                 this.$message.success(res.msg);
            }
          });     
          this.search();     
        } else {
          this.$message.warning(res.msg);
        }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },

    handleSelectionChange(val) {
      this.check = val;
    },
    

    //获取列表数据
    getListData() {
      var data = this.searchObj;
      data.page = this.searchContent.currentPage;
      data.pageSize = this.searchContent.pageSize;
        this.$http.get('/admin/points/index.php?act=PointsSettle&op=settleList', {params: data}).then((res) => {
          if (res.code === 1) {
            this.total = res.data.totalCount;
            this.goodsList = res.data.list.map(item => {
              if(item.point_inner == 1) item.point_inner_checked = true
              else item.point_inner_checked = false
              return item
            })
            // this.$message.success( res.msg);
            // this.getListData();
          } else {
            this.total = 0;
            this.goodsList = [];
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
 
     formatDate(datetime) {
      var date = new Date(datetime); //datetime时间戳为13位毫秒级别,如为10位需乘1000
      var month = ("0" + (date.getMonth() + 1)).slice(-2),	// getMonth是从1-11,所以需要加1
          sdate = ("0" + date.getDate()).slice(-2),	// -2表示从倒数第二个元素开始截取
          hour = ("0" + date.getHours()).slice(-2),
          minute = ("0" + date.getMinutes()).slice(-2),
          second = ("0" + date.getSeconds()).slice(-2);
      var thatDate = date.getFullYear() + "-" + month + "-" + sdate + " " + hour + ":" + minute + ":" + second;
      // 返回
      return thatDate;
    }, 

    //搜索条件汇总
    search(page) {
      this.searchContent.currentPage = Number(page) ? Number(page) : 1;
      let add_time = this.searchContent.add_time;
      this.searchObj = objScreen({
        add_time_begin: add_time[0]?this.formatDate(add_time[0]*1000 && parseInt(add_time[0].getTime())):'',
        add_time_end: add_time[1]?this.formatDate(add_time[1]*1000 && parseInt((add_time[1].getTime()))).replace('00:00:00','23:59:59'):'',
        order_sn: this.searchContent.order_sn,//订单编号
        member_name: this.searchContent.member_name,//会员名称
        mobile: this.searchContent.mobile,//手机号
        order_status:this.searchContent.order_status,//订单状态
        review_page : this.searchContent.review_page,//是否复核页面
        type : this.searchContent.type,//1积分订单 2是在线支付
        store_id: this.searchContent.store_id,//店铺id
        is_settled:this.searchContent.is_settled,//是否结算
        is_review:this.searchContent.is_review,//是否复核
        is_paid:this.searchContent.is_paid,//是否已打款
        settlement_store_id:this.searchContent.settlement_store_id,//承担商家
      });
      this.getListData();
    },

    //重置
    resetSearchData() {
      // console.log(this.$refs);
      this.$refs["searchForm"].resetFields();
      this.searchContent.is_bill = "";
      this.searchContent.is_settled = "";
      this.searchContent.store_id = '';
      this.searchContent.settlement_store_id = '';      
      this.search();
    },
    

    //导出检索数据
    expertData() {
      var host;
      if (this.$store.state.isServer) {
        host = location.host.replace("admin", "api");
      } else {
        host = location.host + "/api";
      }
      var url =
        location.protocol +
        "//" +
        host +
        "/admin/points/index.php?act=PointsSettle&op=settleList&is_export=1";
      var searchData = this.searchObj;
      for (var key in searchData) {
        if (
          !(
            searchData[key] === null ||
            searchData[key] === "" ||
            searchData[key] === undefined ||
            key === "page" ||
            key === "pageSize" ||
            key === "currentPage"
          )
        ) {
          url += "&" + key + "=" + searchData[key];
        }
      }
      // console.log(url);
      window.location.href = url;
    },


    handleSizeChange(pageSize) {
      localStorage.setItem("pageSize", pageSize);
      this.searchContent.pageSize = pageSize;
      this.searchContent.currentPage = 1;
      this.search();
    },

    handleCurrentChange(page) {
      this.searchContent.currentPage = page;
      this.search(page);
    },
    //复核
    buttonDeal(id,operate) {
      if(operate){
            this.$message.error('无法操作');
            return false;
      }        
      this.$http
        .post("/admin/points/index.php?act=PointsSettle&op=review", {
          id: id,
        })
        .then((res) => {
          if (res.code === 1) {
            this.search();
            this.$message.success(res.msg);
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },

    //打款
    buttonPaid(id,operate){
      if(operate){
            this.$message.error('无法操作');
            return false;
      }        
      this.$http
        .post("/admin/points/index.php?act=PointsSettle&op=payConfirm", {
          id: id,
        })
        .then((res) => {
          if (res.code === 1) {
            this.search();
            this.$message.success(res.msg);
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    //撤回复核
    billRollback(id,operate) {
      if(operate){
            this.$message.error('无法操作');
            return false;
      }        
      this.$http
        .post("/admin/points/index.php?act=PointsSettle&op=reviewWithdraw", {
          id: id,
        })
        .then((res) => {
          if (res.code === 1) {
            this.search();
            this.$message.success(res.msg);
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    //撤回打款
    paidback(id,operate) {
      if(operate){
            this.$message.error('无法操作');
            return false;
      }        
      this.$http
        .post("/admin/points/index.php?act=PointsSettle&op=payConfirmWithdraw", {
          id: id,
        })
        .then((res) => {
          if (res.code === 1) {
            this.search();
            this.$message.success(res.msg);
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },

  },
  mounted() {
    resize(this);
  },
};
</script>
<style lang="scss" scoped>
.color-1 {
  color: #ff3300;
}
.bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-content-input {
  width: 200px;
}
.tpyeDown {
  color: #409eff;
  margin-top: 10px;
}

</style>
